import React, { Component } from "react";
import {
  Card,
  Col,
  Row,
  Carousel,
  Statistic,
  Divider,
  Avatar,
  Space,
  List,
  Badge,
} from "antd";
import { Pie, measureTextWidth, Column, Radar, Line } from "@ant-design/charts";
import { LeftCircleOutlined, RightCircleOutlined } from "@ant-design/icons";
import axios from "axios";
import { getToken } from "../../utils/auth";
import { GetTradeInfo, Orderlist } from "../../services/auth";

export default class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      products: [],
      orderSum: 0,
      orderTypeSum: [],
      saleCountM: [],
      saleSum: 0,
      dataSource: [],
      WQuoCount: 0,
      WInqCount: 0,
    };
  }

  // 用于判断状态的函数，帮助生成badge
  judgeStatus = (status) => {
    switch (status) {
      case "已完成":
        return "success";
      case "待发送":
        return "error";
      case "待发货":
        return "processing";
      case "待付款":
        return "warning";
      default:
        return "default";
    }
  };

  //获取图表数据
  componentDidMount() {
    axios.get("http://friday.nat100.top/getCarousel").then(
      (response) => {
        this.setState({
          products: response.data,
        });
        console.log(this.state.products);
      },
      (error) => {
        console.log("失败了", error);
      }
    );
    GetTradeInfo(JSON.parse(getToken()).company_id).then(
      (response) => {
        console.log(response.data)
        this.setState({
          orderSum: response.data.orderSum,
          orderTypeSum: response.data.orderTypeSum,
          saleCountM: response.data.saleCountM,
          saleSum: response.data.saleSum,
          WInqCount: response.data.WInqCount,
          WQuoCount: response.data.WQuoCount,
        });
        console.log(response.data);
      },
      (error) => {
        console.log("失败了", error);
      }
    );
    Orderlist(JSON.parse(getToken()).id).then(
      (response) => {
        //拿到我们想要渲染的数据(res)
        this.setState({
          dataSource: response.data,
        });
      },
      (error) => {
        console.log("失败了", error);
      }
    );
  }

  handlePrev = () => {
    this.img.prev();
  };

  handleNext = () => {
    this.img.next();
  };
  render() {
    var salecount = [
      { month: "2021-01", amount: 230020 },
      { month: "2021-02", amount: 323793 },
      { month: "2021-03", amount: 310203 },
      { month: "2021-04", amount: 450452 },
      { month: "2021-05", amount: 298081 },
      { month: "2021-06", amount: 343211 },
      { month: "2021-07", amount: 388943 },
      { month: "2021-08", amount: 374561 },
      { month: "2021-09", amount: 451298 },
      { month: "2021-10", amount: 488082 },
      { month: "2021-11", amount: 452511 },
      { month: "2021-12", amount: 347917 },
    ];
    //1.
    var config1 = {
      data: this.state.saleCountM,
      xField: "month",
      yField: "amount",
      height: 200,
      label: {
        position: "middle",
        style: {
          fill: "#FFFFFF",
          opacity: 0.6,
        },
      },
      meta: {
        month: { alias: "月份" },
        amount: { alias: "总消费额" },
      },
      columnStyle: {
        fill: "#1DA57A",
        shadowColor: "#25b864",
        shadowBlur: 10,
        shadowOffsetX: 5,
        shadowOffsetY: 5,
        cursor: "pointer",
      },
    };

    //2.折线图
    var config2 = {
      data: this.state.saleCountM,
      height: 350,
      xField: "month",
      yField: "amount",
      color: "#1DA57A",
      annotations: [
        {
          type: "regionFilter",
          start: ["min", "median"],
          end: ["max", "0"],
          color: "#F4664A",
        },
        {
          type: "text",
          position: ["min", "median"],
          content: "中位数",
          offsetY: -4,
          style: { textBaseline: "bottom" },
        },
        {
          type: "line",
          start: ["min", "median"],
          end: ["max", "median"],
          style: {
            stroke: "#F4664A",
            lineDash: [2, 2],
          },
        },
      ],
    };

    // //3.雷达图
    // const data = [
    //   { name: "引用", star: 10178 },
    //   { name: "口碑", star: 7077 },
    //   { name: "产量", star: 7345 },
    //   { name: "贡献", star: 6029 },
    //   { name: "热度", star: 8060 },
    // ];
    // const config3 = {
    //   data: data.map((d) =>
    //     Object.assign(Object.assign({}, d), {
    //       star: Math.log(d.star).toFixed(2),
    //     })
    //   ),
    //   xField: "name",
    //   yField: "star",
    //   height: 350,
    //   color: "#1DA57A",
    //   meta: {
    //     star: {
    //       alias: "分数",
    //       min: 0,
    //       nice: true,
    //     },
    //   },
    //   xAxis: {
    //     line: null,
    //     tickLine: null,
    //   },
    //   yAxis: {
    //     label: false,
    //     grid: {
    //       alternateColor: "rgba(0, 0, 0, 0.04)",
    //     },
    //   },
    //   // 开启辅助点
    //   point: {},
    //   area: {},
    // };

    //4.环图
    function renderStatistic(containerWidth, text, style) {
      var _measureTextWidth = (0, measureTextWidth)(text, style),
        textWidth = _measureTextWidth.width,
        textHeight = _measureTextWidth.height;
      var R = containerWidth / 2;
      var scale = 0.8;
      if (containerWidth < textWidth) {
        scale = Math.min(
          Math.sqrt(
            Math.abs(
              Math.pow(R, 2) /
                (Math.pow(textWidth / 2, 2) + Math.pow(textHeight, 2))
            )
          ),
          1
        );
      }
      var textStyleStr = "width:".concat(containerWidth, "px;");
      return '<div style="'
        .concat(textStyleStr, ";font-size:")
        .concat(scale, "em;line-height:")
        .concat(scale < 1 ? 1 : "inherit", ';">')
        .concat(text, "</div>");
    }
    var config4 = {
      height: 350,
      appendPadding: 10,
      data: this.state.orderTypeSum,
      angleField: "sum",
      colorField: "status",
      radius: 1,
      innerRadius: 0.64,
      legend: {
        layout: "vertical",
        position: "bottom",
      },
      label: {
        type: "inner",
        offset: "-50%",
        style: { textAlign: "center", fontSize: 18 },
        autoRotate: false,
        content: "{value}",
      },
      statistic: {
        title: {
          offsetY: 0,
          customHtml: function customHtml(container, view, datum) {
            var _container$getBoundin = container.getBoundingClientRect(),
              width = _container$getBoundin.width,
              height = _container$getBoundin.height;
            var d = Math.sqrt(Math.pow(width / 2, 2) + Math.pow(height / 2, 2));
            var text = datum ? datum.status : "总计";
            return renderStatistic(d, text, { fontSize: 20 });
          },
        },
        content: {
          offsetY: 4,
          customHtml: function customHtml(container, view, datum, data) {
            var _container$getBoundin2 = container.getBoundingClientRect(),
              width = _container$getBoundin2.width;
            var text = datum
              ? datum.sum
              : data.reduce(function (r, d) {
                  return r + d.sum;
                }, 0);
            return renderStatistic(width, text, { fontSize: 20 });
          },
        },
      },
      interactions: [
        { type: "element-selected" },
        { type: "element-active" },
        { type: "pie-statistic-active" },
      ],
    };
    return (
      <div style={{ background: "#f0f2f5", margin: "-24px", padding: "24px" }}>
        <Row gutter={[16, 24]}>
          <Col span={16}>
            <Space>
              <Avatar
                size={70}
                src={`http://imgdic.natapp1.cc${JSON.parse(getToken()).avatar}`}
              />
              <div>
                <div style={{ fontSize: 20 }}>
                  &nbsp;&nbsp;欢迎，{JSON.parse(getToken()).name}!
                </div>
                <div style={{ fontSize: 15, color: "gray", paddingTop: "5%" }}>
                  &nbsp;&nbsp;&nbsp;{JSON.parse(getToken()).company_name}
                </div>
              </div>
            </Space>
          </Col>
          <Col span={8}>
            <Space style={{ textAlign: "center" }}>
              <Statistic
                title="未回复询价单数"
                value={this.state.WInqCount}
                precision={0}
                valueStyle={{ color: "#1DA57A" }}
              />
              <Divider type="vertical"></Divider>
              <Statistic
                title="待回复报价单数"
                value={this.state.WQuoCount}
                precision={0}
                valueStyle={{ color: "#1DA57A" }}
              />
              <Divider type="vertical"></Divider>
              <Statistic
                title="总订单数"
                value={this.state.orderSum}
                precision={0}
                valueStyle={{ color: "#1DA57A" }}
              />
            </Space>
          </Col>

          <Col span={24}>
            <Card hoverable style={{ borderRadius: 20 }}>
              <Column {...config1} />
            </Card>
          </Col>
          <Col span={8}>
            <Card hoverable style={{ borderRadius: 20 }}>
              <Pie {...config4} />
            </Card>
          </Col>
          {/* <Col span={8}>
              <Card hoverable style={{borderRadius:20}}>
                <Radar {...config3} />
              </Card>
            </Col> */}
          <Col span={16}>
            <Card hoverable style={{ borderRadius: 20 }}>
              <Line {...config2} />
            </Card>
          </Col>

          <Col>
            <LeftCircleOutlined
              style={{ fontSize: "30px", paddingTop: 200 }}
              onClick={this.handlePrev}
            />
          </Col>
          <Col span={7}>
            <Carousel
              autoplay
              afterChange={this.onChange}
              ref={(dom) => {
                this.img = dom;
              }}
              style={{ margin: "0px 15px" }}
            >
              {this.state.products.map((item, index) => {
                return (
                  <div key={index + 1}>
                    <img
                      src={item}
                      style={{ width: "100%", height: 400 }}
                    ></img>
                  </div>
                );
              })}
            </Carousel>
          </Col>

          <Col>
            <RightCircleOutlined
              style={{ fontSize: "30px", paddingTop: 200 }}
              onClick={this.handleNext}
            />
          </Col>
          <Col span={15}>
            <Card hoverable title="订单列表" style={{ borderRadius: 20 }}>
              <List
                itemLayout="horizontal"
                dataSource={this.state.dataSource}
                renderItem={(item) => (
                  <List.Item
                    extra={
                      <Badge
                        status={this.judgeStatus(item.status)}
                        text={item.status}
                      />
                    }
                  >
                    <List.Item.Meta
                      title={item.id}
                      description={`${item.ship_to_address}  |   ${item.total_price}元  |   ${item.order_date}`}
                    />
                  </List.Item>
                )}
              />
            </Card>
          </Col>
        </Row>
      </div>
    );
  }
}
